package cc.eddic.pratice.programmingparadigms.emp01array.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.emp01array.EmployeeReaderService;

import ch.qos.logback.core.hook.ShutdownHook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

public class ExcelReaderZyzImpl implements EmployeeReaderService {

    private Workbook readWorkbook(String fileName) {
        try {
            FileInputStream file = new FileInputStream(new File(fileName));
            Workbook workbook = new XSSFWorkbook(file);
            return workbook;
        }
        catch (FileNotFoundException e) {
            System.out.print("Filenotefound!!");
        }
        catch (IOException e) {
            System.out.print("io exception");
        }

        return null;
    }


    /**
     * 从 Excel 读取数据
     *
     * @param fileName Excel 文件名
     * @return Employee 数组
     */

    public Employee[] read(String fileName) {

        Workbook workbook = readWorkbook(fileName);
        Sheet sheet = workbook.getSheetAt(3);
        ArrayList<Employee> employeesList = new ArrayList<Employee>();

        Iterator<Row> rowIterator = sheet.rowIterator();
        rowIterator.next();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
//            Iterator<Cell> cellIterator = row.cellIterator();
//            cellIterator.next();

            Employee e = new Employee(
                    row.getCell(1).getRichStringCellValue().getString(),
                    row.getCell(2).getRichStringCellValue().getString(),
                    row.getCell(3).getRichStringCellValue().getString(),
                    row.getCell(4).getRichStringCellValue().getString()
            );

            employeesList.add(e);

        }
        int numEmployees = employeesList.size();
        Employee[] employeesArr = new Employee[numEmployees];
        employeesArr = employeesList.toArray(employeesArr);

        return employeesArr;
    }



}
